package textparser;

import static org.junit.Assert.*;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

import org.junit.Ignore;
import org.junit.Test;


public class StringBuilderTest {

    @Ignore
    public void testReadFile() {
        String indexFile = "C:\\test\\tail.index";
        String findingTest = "\nalgebra";
        
        int blockSize = 5000;
        char[] block = new char[blockSize];
        zeroFill(block);
        StringBuilder builder = new StringBuilder(blockSize);
        boolean found = false;
        
        BufferedReader reader = null;
        
        try {
            reader = createReader(indexFile);        
            
            while(readContentToArray(reader, block) != -1 && !found) {
                builder.append(block);
                int foundPosition = builder.indexOf(findingTest);
                
                if (foundPosition != -1) {
                    found = true;
                    String fullLine = readFullLine(builder, foundPosition + 1);
                    fullLine.trim();
                    //System.out.println(foundPosition);
                    //System.out.println(builder.length());
                    System.out.println(fullLine);
                } else {
                    builder.replace(0, builder.length(), "");
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        assertTrue(found);
        
    }
    
    private void zeroFill(char[] block) {
       Arrays.fill(block, ' '); 
    }
    
    private int readContentToArray(BufferedReader reader, char[] array) throws IOException {
        return reader.read(array);
    }
    
    private BufferedReader createReader(String file) throws FileNotFoundException {
        return new BufferedReader(new FileReader(file));
    }
    
    private String readFullLine(StringBuilder builder, int startPosition) {
        int endPosition = startPosition + 30;
        if (endPosition >= builder.length()) {
            endPosition = builder.length();
        }
        String fullLine =  builder.substring(startPosition, endPosition);
        return fullLine.trim();
    }
    
    @Test
    public void testInternalStringBuilder() {
        char[] external = { ' ', ' ', 'n', ' ', ' ' };

        
        String string = new String(external);
        
        ;
        
        System.out.println(string.trim());
    }
    
}
